import { createRouter, createWebHistory } from 'vue-router'
import { showToast } from "vant";
import store from '../store'
const routes = [
  {
    path: '/',
    name: '/',
    redirect: '/main/menu'
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/Main.vue'),
    children: [{
      path: 'menu',
      name: "menu",
      component: () => import('../views/Menu.vue'),
      meta: { index: 1 }
    }, {
      path: 'order',
      name: "order",
      component: () => import('../views/Order.vue'),
      // hasLogin表示需要登录后才能访问该路由
      meta: { index: 2, hasLogin: true }
    }, {
      path: 'shopCart',
      name: "shopCart",
      component: () => import('../views/ShopCart.vue'),
      meta: { index: 3, hasLogin: true }
    }, {
      path: 'user',
      name: "user",
      component: () => import('../views/User.vue'),
      meta: { index: 4 }
    }]
  },
  {
    path: "/searchFood",
    name: "searchFood",
    component: () => import('../views/SearchFood.vue'),
    meta: { index: 5 }
  }, {
    path: "/foodDetail/:id",
    name: "foodDetail",
    component: () => import("../views/FoodDetail.vue"),
    meta: { index: 6 }
  },
  {
    path: "/login",
    name: "login",
    component: () => import('../views/Login.vue'),
    meta: { index: 5 }
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/Register.vue"),
    meta: { index: 6 }
  },
  {
    path: "/checkOrder",
    name: "checkOrder",
    component: () => import("../views/CheckOrder.vue"),
    meta: { index: 5, hasLogin: true }
  },
  {
    path: "/address",
    name: "address",
    component: () => import("../views/Address.vue"),
    meta: { index: 6, hasLogin: true }
  },
  {
    path: "/addAddress",
    name: "addAddress",
    component: () => import("../views/AddAddress.vue"),
    meta: { index: 7, hasLogin: true }
  },
  {
    path: "/editAddress",
    name: "editAddress",
    component: () => import("../views/EditAddress.vue"),
    meta: { index: 7, hasLogin: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from) => {
  if (to.meta.hasLogin === true) {
    if (!store.state.userInfo) {
      showToast("请登录。。。")
      // 把要去的url保存下来，等会登录以后再跳转过去
      return to.path = { name: "login", query: { redirect: to.fullPath } }
    }
  }
})

export default router
